package com.todod.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.todod.common.util.SnowflakeIdGenerator;
import com.todod.dto.RoleDto;
import com.todod.entity.QueryEntry;
import com.todod.exception.CustomException;
import com.todod.mapper.RoleMapper;
import com.todod.model.Role;
import com.todod.service.IRoleService;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author gsh
 * @since 2020-11-23
 */
@Service
@Transactional
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {
	@Override
	public IPage<RoleDto> getList(QueryEntry queryEntry) {
		Page<RoleDto> page = new Page<>(queryEntry.getPage(), queryEntry.getLimit());
		RoleMapper roleMapper = this.getBaseMapper();
		IPage<RoleDto> list = roleMapper.getList(page, queryEntry);
		return list;
	}

	@Override
	public void save(Long userId, Role role) {
		if (role.getId() == null) {
			// 角色code是否重复
			Role byCode = getByCode(role.getCode());
			if (null != byCode) {
				throw new CustomException("角色代码重复！请重新输入");
			}
			role.setId(SnowflakeIdGenerator.getId());
			role.setCreateUserId(userId);
			role.setCreateTime(new Date());

			save(role);
		} else {
			Role role2 = getById(role.getId());
			role2.setModifyUserId(userId);
			role2.setModifyTime(new Date());

			role2.setName(role.getName());
			role2.setDepartid(role.getDepartid());
			updateById(role2);
		}

	}

	@Override
	public Role getByCode(String code) {
		QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("sr_code", code);
		Role role = getOne(queryWrapper);
		return role;
	}

	@Override
	public List<Role> getByCompanyId(Long departid) {
		QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("sr_department_id", departid);
		List<Role> list = list(queryWrapper);
		return list;
	}

}
